Completed
Push — master ( e88c19...17669b )
by Rain
03:00
created

AbstractAjax.js ➔ ... ➔ ???

Size

Total Lines 113

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
nc 11712
nop 2
dl 0
loc 113

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
2
import $ from '$';
3
import Promise from 'Promise';
4
5
import {ajax} from 'Common/Links';
6
import {microtime, isUnd, isNormal, pString, pInt, inArray} from 'Common/Utils';
7
import {DEFAULT_AJAX_TIMEOUT, TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT} from 'Common/Consts';
8
import {StorageResultType, Notification} from 'Common/Enums';
9
import {data as GlobalsData} from 'Common/Globals';
10
import * as Plugins from 'Common/Plugins';
11
import * as Settings from 'Storage/Settings';
12
13
import {AbstractBasicPromises} from 'Promises/AbstractBasic';
14
15
class AbstractAjaxPromises extends AbstractBasicPromises
16
{
17
	constructor() {
18
		super();
19
		this.oRequests = {};
20
		this.clear();
21
	}
22
23
	clear() {
24
		this.oRequests = {};
25
	}
26
27
	abort(sAction, bClearOnly) {
28
		if (this.oRequests[sAction])
29
		{
30
			if (!bClearOnly && this.oRequests[sAction].abort)
31
			{
32
				this.oRequests[sAction].__aborted__ = true;
33
				this.oRequests[sAction].abort();
34
			}
35
36
			this.oRequests[sAction] = null;
37
			delete this.oRequests[sAction];
38
		}
39
40
		return this;
41
	}
42
43
	ajaxRequest(action, isPost, timeOut, params, additionalGetString, fTrigger) {
44
45
		return new Promise((resolve, reject) => {
46
47
			const start = microtime();
48
49
			timeOut = isNormal(timeOut) ? timeOut : DEFAULT_AJAX_TIMEOUT;
50
			additionalGetString = isUnd(additionalGetString) ? '' : pString(additionalGetString);
51
52
			if (isPost)
53
			{
54
				params.XToken = Settings.appSettingsGet('token');
55
			}
56
57
			Plugins.runHook('ajax-default-request', [action, params, additionalGetString]);
58
59
			this.setTrigger(fTrigger, true);
60
61
			const oH = $.ajax({
62
				type: isPost ? 'POST' : 'GET',
63
				url: ajax(additionalGetString),
64
				async: true,
65
				dataType: 'json',
66
				data: isPost ? (params || {}) : {},
67
				timeout: timeOut,
68
				global: true
69
			}).always((data, textStatus) => {
70
71
				let
72
					isCached = false,
73
					errorData = null;
74
75
				if (data && data.Time)
76
				{
77
					isCached = pInt(data.Time) > microtime() - start;
78
				}
79
80
				// backward capability
81
				let type = '';
82
				switch (true)
83
				{
84
					case 'success' === textStatus && data && data.Result && action === data.Action:
85
						type = StorageResultType.Success;
86
						break;
87
					case 'abort' === textStatus && (!data || !data.__aborted__):
88
						type = StorageResultType.Abort;
89
						break;
90
					default:
91
						type = StorageResultType.Error;
92
						break;
93
				}
94
95
				Plugins.runHook('ajax-default-response', [
96
					action, StorageResultType.Success === type ? data : null, type, isCached, params
97
				]);
98
99
				if ('success' === textStatus)
100
				{
101
					if (data && data.Result && action === data.Action)
102
					{
103
						data.__cached__ = isCached;
104
						resolve(data);
105
					}
106
					else if (data && data.Action)
107
					{
108
						errorData = data;
109
						reject(data.ErrorCode ? data.ErrorCode : Notification.AjaxFalse);
110
					}
111
					else
112
					{
113
						errorData = data;
114
						reject(Notification.AjaxParse);
115
					}
116
				}
117
				else if ('timeout' === textStatus)
118
				{
119
					errorData = data;
120
					reject(Notification.AjaxTimeout);
121
				}
122
				else if ('abort' === textStatus)
123
				{
124
					if (!data || !data.__aborted__)
125
					{
126
						reject(Notification.AjaxAbort);
127
					}
128
				}
129
				else
130
				{
131
					errorData = data;
132
					reject(Notification.AjaxParse);
133
				}
134
135
				if (this.oRequests[action])
136
				{
137
					this.oRequests[action] = null;
138
					delete this.oRequests[action];
139
				}
140
141
				this.setTrigger(fTrigger, false);
142
143
				if (errorData)
144
				{
145
					if (-1 < inArray(errorData.ErrorCode, [
146
						Notification.AuthError, Notification.AccessError,
147
						Notification.ConnectionError, Notification.DomainNotAllowed, Notification.AccountNotAllowed,
148
						Notification.MailServerError,	Notification.UnknownNotification, Notification.UnknownError
149
					]))
150
					{
151
						GlobalsData.iAjaxErrorCount += 1;
152
					}
153
154
					if (Notification.InvalidToken === errorData.ErrorCode)
155
					{
156
						GlobalsData.iTokenErrorCount += 1;
157
					}
158
159
					if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount)
160
					{
161
						if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload)
162
						{
163
							GlobalsData.__APP__.loginAndLogoutReload(false, true);
164
						}
165
					}
166
167
					if (errorData.ClearAuth || errorData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount)
168
					{
169
						if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken)
170
						{
171
							GlobalsData.__APP__.clearClientSideToken();
172
						}
173
174
						if (GlobalsData.__APP__ && !errorData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload)
175
						{
176
							GlobalsData.__APP__.loginAndLogoutReload(false, true);
177
						}
178
					}
179
				}
180
181
			});
182
183
			if (oH)
184
			{
185
				if (this.oRequests[action])
186
				{
187
					this.oRequests[action] = null;
188
					delete this.oRequests[action];
189
				}
190
191
				this.oRequests[action] = oH;
192
			}
193
		});
194
	}
195
196
	getRequest(sAction, fTrigger, sAdditionalGetString, iTimeOut) {
197
198
		sAdditionalGetString = isUnd(sAdditionalGetString) ? '' : pString(sAdditionalGetString);
199
		sAdditionalGetString = sAction + '/' + sAdditionalGetString;
200
201
		return this.ajaxRequest(sAction, false, iTimeOut, null, sAdditionalGetString, fTrigger);
202
	}
203
204
	postRequest(action, fTrigger, params, timeOut) {
205
206
		params = params || {};
207
		params.Action = action;
208
209
		return this.ajaxRequest(action, true, timeOut, params, '', fTrigger);
210
	}
211
}
212
213
export {AbstractAjaxPromises, AbstractAjaxPromises as default};
214